package com.dominator.utils.qiniu;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.dominFramework.core.id.SystemIdUtils;
import com.dominFramework.core.utils.SystemUtils;
import org.springframework.web.multipart.MultipartFile;

import com.dominator.utils.system.PropertiesLoader;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;

/**
 * 七牛文件上传类
 * 
 * @author DL
 *
 */
public class QiniuUploadFile {

	public static PropertiesLoader propertiesLoader = new PropertiesLoader("sysconfig.properties");

	/**
	 * 七牛配置
	 */
	public static final String QN_accessKey = propertiesLoader.getProperty("qn_accessKey");
	public static final String QN_secretKey = propertiesLoader.getProperty("qn_secretKey");
	public static final String QN_bucket = propertiesLoader.getProperty("qn_bucket");
	public static final String QN_https_url = "";
	public static final String QN_http_url = propertiesLoader.getProperty("qn_http_url");

	/**
	 * 文件上传
	 * 
	 * @param file
	 * @param bucket
	 * @return
	 */
	public static String upload(MultipartFile file, String bucket) {
		String url = "";
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone0());
		// ...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		// ...生成上传凭证，然后准备上传
		String accessKey = QN_accessKey;
		String secretKey = QN_secretKey;
		if (SystemUtils.isEmpty(bucket)) {
			bucket = QN_bucket;// 七牛存储空间
		}
		String originalFileName = file.getOriginalFilename();
		System.out.println("原始名称：" + originalFileName + "." + originalFileName.lastIndexOf("."));

		String fileType = file.getContentType();
		System.out.println("文件类型：" + fileType);
		// 默认不指定key的情况下，以文件内容的hash值作为文件名
		String key = SystemIdUtils.uuid() + "." + fileType.split("/")[1];
		System.out.println("指定的名称：" + key);
		// 将流转换成byte数组
		byte[] uploadBytes = null;
		try {
			uploadBytes = file.getBytes();
		} catch (IOException e) {
			e.printStackTrace();
			return url;
		}
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);// 获取上传Token
		url = uploadPicture(url, uploadManager, key, upToken, uploadBytes);

		return url;

	}

	/**
	 * 文件上传
	 * 
	 * @param uploadBytes
	 * @param type
	 * @return
	 */
	public static String upload(byte[] uploadBytes, String type) {
		String url = "";
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone0());
		// ...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		// ...生成上传凭证，然后准备上传
		String accessKey = QN_accessKey;
		String secretKey = QN_secretKey;
		String key = SystemIdUtils.uuid() + "." + type;
		System.out.println("指定的名称：" + key);
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(QN_bucket);// 获取上传Token
		url = uploadPicture(url, uploadManager, key, upToken, uploadBytes);

		return url;

	}

	/**
	 * 文件上传
	 * 
	 * @param base64Str
	 * @param type
	 * @return
	 * @throws IOException
	 */
	public static String upload(String base64Str, String type) throws IOException {
		String url = "";
		// 构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone0());
		// ...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		// ...生成上传凭证，然后准备上传
		String accessKey = QN_accessKey;
		String secretKey = QN_secretKey;
		String key = SystemIdUtils.uuid() + "." + type;
		System.out.println("指定的名称：" + key);
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(QN_bucket);// 获取上传Token
		BASE64Decoder decoder = new BASE64Decoder();
		base64Str=base64Str.split(",")[1];
		byte[] uploadBytes = decoder.decodeBuffer(base64Str);
		for (int i = 0; i < uploadBytes.length; ++i) {
			if (uploadBytes[i] < 0) {// 调整异常数据
				uploadBytes[i] += 256;
			}
		}
		url = uploadPicture(url, uploadManager, key, upToken, uploadBytes);

		return url;

	}

	/**
	 * 七牛云上传图片
	 * @param url
	 * @param uploadManager
	 * @param key
	 * @param upToken
	 * @param uploadBytes
	 * @return
	 */
	private static String uploadPicture(String url, UploadManager uploadManager, String key, String upToken, byte[] uploadBytes) {
		try {
			Response response = uploadManager.put(uploadBytes, key, upToken);
			// 解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			System.out.println(putRet.key);
			System.out.println(putRet.hash);
			url = QN_http_url + putRet.key;

		} catch (QiniuException ex) {
			Response r = ex.response;
			System.err.println(r.toString());

		}
		return url;
	}

	/**
	 * 上传图片
	 * @param bufferedImage
	 * @param type
	 * @return
	 */
	public static String upload(BufferedImage bufferedImage,String type){
		ByteArrayOutputStream os=new ByteArrayOutputStream();//新建流。
		try {
			ImageIO.write(bufferedImage, type, os);//利用ImageIO类提供的write方法，将bi以png图片的数据模式写入流。
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte b[]=os.toByteArray();//从流中获取数据数组。
        String url=upload(b,type);
		return url;
	}

}
